package com.gable.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by mj on 2018/1/17.
 */
@Component
@ServerEndpoint(value = "/webSocketJoin",configurator = SpringConfigurator.class)
public class WebSocketJoin {

    Logger log = Logger.getLogger(WebSocketJoin.class);
    public static Set<Session> sessionSet = new HashSet<Session>();
    //sessionID 和 用户ID 关系
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        sessionSet.add(session);
        System.out.println("客户端"+session.getId()+"连接加入！当前在线人数为"+sessionSet.size());
    }

    /**
     * 连接关闭调用的方法
     * 需要将两个MAP中的对应的对象都移除
     */
    @OnClose
    public void onClose(Session session){
        String sessionId = session.getId();
        sessionSet.remove(session);
        System.out.println("客户端："+session.getId()+"关闭！当前在线人数为"+sessionSet.size());
    }

    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        String sessionId = session.getId();
        sessionSet.remove(session);
        System.out.println("客户端："+session.getId()+"发生错误:当前在线人数为"+sessionSet.size());
    }

    /**
     * 推送给接收人
     * @param message
     * @throws IOException
     */
    public void sendMessage(Set<Session> sessions,String message) throws IOException{
        for(Session session : sessions){
            Session toSession = session;
            //只推送给“在线的用户”
            if(toSession != null){
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("html",message);
                map.put("content",message);
                toSession.getAsyncRemote().sendText(JSON.toJSONString(map));
            }
        }
    }
}
